from .functions import *

from .CommandDataPackage import CommandDataPackage
from .ResponseDataPackage import ResponseDataPackage
from .CommandPackage import CommandPackage
from .ResponsePackage import ResponsePackage

class BasicSession(object):
	"""docstring for BasicSession"""
	def __init__(self, debug = False):
		super(BasicSession, self).__init__()
		self.debug = debug

	def connect(self,
			port = "/dev/tty.SLAB_USBtoUART",
			baudrate = 115200,
			timeout = None):
		self.connection = getConnection(port, baudrate, timeout)
		if self.connection: return True
		else: return False

	def sendCommandMessage(self, cmd, data = '', debug = False):
		pkg = CommandPackage(cmd = cmd, data = data)
		if debug or self.debug: print("Send command: ", pkg.getPackageString())
		return self.connection.write(pkg.getPackageData())
	def readResponseMessage(self, debug = False, allowedReturnCodes = []):
		resData = self.connection.read(26)
		resPkg = ResponsePackage(packageString = resData.encode('hex'))
		if debug or self.debug: print("Receive response: ", resPkg.getPackageString())
		if resPkg.ret == 0: return resPkg.data
		elif resPkg.ret in allowedReturnCodes: return resPkg.data
		else: return None
	def sendCommandData(self, cmd, data = '', debug = False):
		pkg = CommandDataPackage(cmd = cmd, data = data)
		if debug or self.debug: print("Send command data: ", pkg.getPackageString())
		return self.connection.write(pkg.getPackageData())
	def readResponseData(self, data_len, debug = False, allowedReturnCodes = []):
		resData = self.connection.read(12 + data_len)
		resPkg = ResponseDataPackage(packageString = resData.encode('hex'))
		if debug or self.debug: print("Receive response data: ", resPkg.getPackageString())
		if resPkg.ret == 0: return resPkg.data
		elif resPkg.ret in allowedReturnCodes: return resPkg.data
		else: return None

	def sendCommand(self, cmd, cmd_data = "", data = None):
		self.sendCommandMessage(cmd, cmd_data)
		if data: self.sendCommandData(cmd, data)
	def readResponse(self, withData = True):
		res_data = self.readResponseMessage()
		if res_data == None: return None
		if not withData: return res_data
		if len(res_data) != 4: return res_data
		data_len = parseWord(res_data)
		res_data = self.readResponseData(data_len)
		return res_data